from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import subprocess
import os

@csrf_exempt
def run_transfer(request):
    if request.method == 'POST':
        try:
            # 获取 Transfer.py 文件的路径
            script_path = os.path.join(os.path.dirname(__file__), 'Util', 'Transfer.py')

            # 使用 subprocess 调用 Python 脚本
            result = subprocess.run(['python', script_path], capture_output=True, text=True)

            # 如果脚本执行成功，返回 JSON 响应
            if result.returncode == 0:
                return JsonResponse({'message': 'Transfer started successfully'}, status=200)
            else:
                return JsonResponse({'message': 'Error running Transfer.py', 'error': result.stderr}, status=500)
        except Exception as e:
            return JsonResponse({'message': f'Error: {str(e)}'}, status=500)
    return JsonResponse({'message': 'Invalid request method'}, status=400)